package cn.idongjia.logloader.mongo;

import com.mongodb.MongoClient;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;

import java.util.Properties;

public class DataStoreProvider {
    private static final String ADDRESSES_KEY = "mongo.addresses";
    private static final String DEFAULT_ADDRESSES = "127.0.0.1:27017";
    private static final String DATABASE_KEY = "mongo.database";
    private static final String DEFAULT_DATABASE = "lts";
    private static final String USERNAME = "mongo.username";
    private static final String PASSWORD = "mongo.password";

    public static Datastore getDataStore(Properties properties) {

        String[] addresses = new String[]{properties.getProperty(ADDRESSES_KEY, DEFAULT_ADDRESSES)};
        String database = properties.getProperty(DATABASE_KEY, DEFAULT_DATABASE);
        String username = properties.getProperty(USERNAME);
        String pwd = properties.getProperty(PASSWORD);
        Datastore datastore = null;
        try {
            Morphia morphia = new Morphia();
            MongoFactoryBean mongoFactoryBean = new MongoFactoryBean(addresses, username, database, pwd);
            MongoClient mongo = mongoFactoryBean.createInstance();
            datastore = morphia.createDatastore(mongo, database);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return datastore;
    }
}
